import React, { useState, useEffect } from 'react';
import {
    Box,
    Paper,
    TextField,
    Button,
    Typography,
    Grid,
    MenuItem,
    FormControl,
    InputLabel,
    Select,
    Alert,
    CircularProgress,
    Slider,
    InputAdornment
} from '@mui/material';
import { ChromePicker } from 'react-color';
import { motion, AnimatePresence } from 'framer-motion';
import { useModelContext } from '../contexts/ModelContext';

const GeometryModelForm = ({ initialData = {}, isEdit = false, onSubmit, onCancel }) => {
    const { geometryTypes, geometryTypesLoading } = useModelContext();

    // 基本信息
    const [name, setName] = useState(initialData.name || '');
    const [description, setDescription] = useState(initialData.description || '');

    // 几何体属性
    const [geometryType, setGeometryType] = useState(initialData.geometry?.type || '');
    const [color, setColor] = useState(initialData.geometry?.color || '#1976D2');
    const [showColorPicker, setShowColorPicker] = useState(false);

    // 尺寸属性 - 立方体
    const [cubeWidth, setCubeWidth] = useState(initialData.geometry?.dimensions?.width || 2);
    const [cubeHeight, setCubeHeight] = useState(initialData.geometry?.dimensions?.height || 2);
    const [cubeDepth, setCubeDepth] = useState(initialData.geometry?.dimensions?.depth || 2);

    // 尺寸属性 - 球体
    const [sphereRadius, setSphereRadius] = useState(initialData.geometry?.dimensions?.radius || 1);
    const [sphereSegments, setSphereSegments] = useState(initialData.geometry?.dimensions?.segments || 32);

    // 位置
    const [positionX, setPositionX] = useState(initialData.geometry?.position?.x || 0);
    const [positionY, setPositionY] = useState(initialData.geometry?.position?.y || 0);
    const [positionZ, setPositionZ] = useState(initialData.geometry?.position?.z || 0);

    // 旋转
    const [rotationX, setRotationX] = useState(initialData.geometry?.rotation?.x || 0);
    const [rotationY, setRotationY] = useState(initialData.geometry?.rotation?.y || 0);
    const [rotationZ, setRotationZ] = useState(initialData.geometry?.rotation?.z || 0);

    // 表单状态
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [validationErrors, setValidationErrors] = useState({});

    // 默认几何体类型选项，当API未返回数据时使用
    const defaultGeometryTypes = [
        { type: 'cube', displayName: '立方体' },
        { type: 'sphere', displayName: '球体' },
        { type: 'cylinder', displayName: '圆柱体' },
        { type: 'cone', displayName: '圆锥体' },
        { type: 'plane', displayName: '平面' }
    ];

    // 使用的几何体类型列表 - 优先使用API返回的，如果为空则使用默认值
    const effectiveGeometryTypes = (geometryTypes && geometryTypes.length > 0)
        ? geometryTypes
        : defaultGeometryTypes;

    useEffect(() => {
        if (initialData.geometry) {
            setGeometryType(initialData.geometry.type);
            setColor(initialData.geometry.color);

            // 根据几何体类型设置相应的尺寸属性
            if (initialData.geometry.type === 'cube') {
                setCubeWidth(initialData.geometry.dimensions.width);
                setCubeHeight(initialData.geometry.dimensions.height);
                setCubeDepth(initialData.geometry.dimensions.depth);
            } else if (initialData.geometry.type === 'sphere') {
                setSphereRadius(initialData.geometry.dimensions.radius);
                setSphereSegments(initialData.geometry.dimensions.segments);
            }

            // 设置位置和旋转
            if (initialData.geometry.position) {
                setPositionX(initialData.geometry.position.x);
                setPositionY(initialData.geometry.position.y);
                setPositionZ(initialData.geometry.position.z);
            }

            if (initialData.geometry.rotation) {
                setRotationX(initialData.geometry.rotation.x);
                setRotationY(initialData.geometry.rotation.y);
                setRotationZ(initialData.geometry.rotation.z);
            }
        }
    }, [initialData]);

    // 验证表单
    const validateForm = () => {
        const errors = {};

        if (!name.trim()) errors.name = '请输入模型名称';
        if (!geometryType) errors.geometryType = '请选择几何体类型';

        setValidationErrors(errors);
        return Object.keys(errors).length === 0;
    };

    // 处理提交
    const handleSubmit = async (e) => {
        e.preventDefault();

        if (!validateForm()) return;

        setLoading(true);
        setError(null);

        try {
            // 构建几何体数据
            let dimensions = {};
            if (geometryType === 'cube') {
                dimensions = {
                    width: Number(cubeWidth),
                    height: Number(cubeHeight),
                    depth: Number(cubeDepth)
                };
            } else if (geometryType === 'sphere') {
                dimensions = {
                    radius: Number(sphereRadius),
                    segments: Number(sphereSegments)
                };
            } else if (geometryType === 'cylinder') {
                dimensions = {
                    radius: Number(sphereRadius),
                    height: Number(cubeHeight),
                    segments: Number(sphereSegments)
                };
            } else if (geometryType === 'cone') {
                dimensions = {
                    radius: Number(sphereRadius),
                    height: Number(cubeHeight),
                    segments: Number(sphereSegments)
                };
            } else if (geometryType === 'plane') {
                dimensions = {
                    width: Number(cubeWidth),
                    height: Number(cubeHeight)
                };
            }

            const modelData = {
                name,
                description,
                geometry: {
                    type: geometryType,
                    color,
                    dimensions,
                    position: {
                        x: Number(positionX),
                        y: Number(positionY),
                        z: Number(positionZ)
                    },
                    rotation: {
                        x: Number(rotationX),
                        y: Number(rotationY),
                        z: Number(rotationZ)
                    }
                }
            };

            await onSubmit(modelData);
        } catch (err) {
            setError(err.message || '提交表单时发生错误');
        } finally {
            setLoading(false);
        }
    };

    // 渲染几何体特定属性
    const renderGeometryAttributes = () => {
        switch (geometryType) {
            case 'cube':
                return (
                    <Grid container spacing={2}>
                        <Grid item xs={12} sm={4}>
                            <TextField
                                label="宽度"
                                fullWidth
                                type="number"
                                value={cubeWidth}
                                onChange={(e) => setCubeWidth(e.target.value)}
                                InputProps={{
                                    endAdornment: <InputAdornment position="end">单位</InputAdornment>,
                                }}
                                inputProps={{ step: 0.1, min: 0.1 }}
                            />
                        </Grid>
                        <Grid item xs={12} sm={4}>
                            <TextField
                                label="高度"
                                fullWidth
                                type="number"
                                value={cubeHeight}
                                onChange={(e) => setCubeHeight(e.target.value)}
                                InputProps={{
                                    endAdornment: <InputAdornment position="end">单位</InputAdornment>,
                                }}
                                inputProps={{ step: 0.1, min: 0.1 }}
                            />
                        </Grid>
                        <Grid item xs={12} sm={4}>
                            <TextField
                                label="深度"
                                fullWidth
                                type="number"
                                value={cubeDepth}
                                onChange={(e) => setCubeDepth(e.target.value)}
                                InputProps={{
                                    endAdornment: <InputAdornment position="end">单位</InputAdornment>,
                                }}
                                inputProps={{ step: 0.1, min: 0.1 }}
                            />
                        </Grid>
                    </Grid>
                );

            case 'sphere':
                return (
                    <Grid container spacing={2}>
                        <Grid item xs={12} sm={6}>
                            <TextField
                                label="半径"
                                fullWidth
                                type="number"
                                value={sphereRadius}
                                onChange={(e) => setSphereRadius(e.target.value)}
                                InputProps={{
                                    endAdornment: <InputAdornment position="end">单位</InputAdornment>,
                                }}
                                inputProps={{ step: 0.1, min: 0.1 }}
                            />
                        </Grid>
                        <Grid item xs={12} sm={6}>
                            <Box sx={{ width: '100%' }}>
                                <Typography id="segments-slider" gutterBottom>
                                    细分数: {sphereSegments}
                                </Typography>
                                <Slider
                                    value={sphereSegments}
                                    onChange={(e, newValue) => setSphereSegments(newValue)}
                                    aria-labelledby="segments-slider"
                                    step={4}
                                    marks
                                    min={8}
                                    max={64}
                                    valueLabelDisplay="auto"
                                />
                            </Box>
                        </Grid>
                    </Grid>
                );

            case 'cylinder':
            case 'cone':
                return (
                    <Grid container spacing={2}>
                        <Grid item xs={12} sm={4}>
                            <TextField
                                label="半径"
                                fullWidth
                                type="number"
                                value={sphereRadius}
                                onChange={(e) => setSphereRadius(e.target.value)}
                                InputProps={{
                                    endAdornment: <InputAdornment position="end">单位</InputAdornment>,
                                }}
                                inputProps={{ step: 0.1, min: 0.1 }}
                            />
                        </Grid>
                        <Grid item xs={12} sm={4}>
                            <TextField
                                label="高度"
                                fullWidth
                                type="number"
                                value={cubeHeight}
                                onChange={(e) => setCubeHeight(e.target.value)}
                                InputProps={{
                                    endAdornment: <InputAdornment position="end">单位</InputAdornment>,
                                }}
                                inputProps={{ step: 0.1, min: 0.1 }}
                            />
                        </Grid>
                        <Grid item xs={12} sm={4}>
                            <Box sx={{ width: '100%' }}>
                                <Typography id="segments-slider" gutterBottom>
                                    细分数: {sphereSegments}
                                </Typography>
                                <Slider
                                    value={sphereSegments}
                                    onChange={(e, newValue) => setSphereSegments(newValue)}
                                    aria-labelledby="segments-slider"
                                    step={4}
                                    marks
                                    min={8}
                                    max={64}
                                    valueLabelDisplay="auto"
                                />
                            </Box>
                        </Grid>
                    </Grid>
                );

            case 'plane':
                return (
                    <Grid container spacing={2}>
                        <Grid item xs={12} sm={6}>
                            <TextField
                                label="宽度"
                                fullWidth
                                type="number"
                                value={cubeWidth}
                                onChange={(e) => setCubeWidth(e.target.value)}
                                InputProps={{
                                    endAdornment: <InputAdornment position="end">单位</InputAdornment>,
                                }}
                                inputProps={{ step: 0.1, min: 0.1 }}
                            />
                        </Grid>
                        <Grid item xs={12} sm={6}>
                            <TextField
                                label="高度"
                                fullWidth
                                type="number"
                                value={cubeHeight}
                                onChange={(e) => setCubeHeight(e.target.value)}
                                InputProps={{
                                    endAdornment: <InputAdornment position="end">单位</InputAdornment>,
                                }}
                                inputProps={{ step: 0.1, min: 0.1 }}
                            />
                        </Grid>
                    </Grid>
                );

            default:
                return null;
        }
    };

    return (
        <Box component="form" onSubmit={handleSubmit} noValidate>
            <Paper sx={{ p: 3, mb: 3 }}>
                <Typography variant="h6" gutterBottom>
                    基本信息
                </Typography>

                <Grid container spacing={2}>
                    <Grid item xs={12}>
                        <TextField
                            label="模型名称"
                            fullWidth
                            required
                            value={name}
                            onChange={(e) => setName(e.target.value)}
                            error={!!validationErrors.name}
                            helperText={validationErrors.name}
                        />
                    </Grid>
                    <Grid item xs={12}>
                        <TextField
                            label="描述"
                            fullWidth
                            multiline
                            rows={3}
                            value={description}
                            onChange={(e) => setDescription(e.target.value)}
                        />
                    </Grid>
                </Grid>
            </Paper>

            <Paper sx={{ p: 3, mb: 3 }}>
                <Typography variant="h6" gutterBottom>
                    几何体属性
                </Typography>

                <Grid container spacing={3}>
                    <Grid item xs={12} sm={6}>
                        <FormControl fullWidth error={!!validationErrors.geometryType}>
                            <InputLabel>几何体类型</InputLabel>
                            <Select
                                value={geometryType}
                                onChange={(e) => setGeometryType(e.target.value)}
                                label="几何体类型"
                                disabled={geometryTypesLoading || isEdit}
                            >
                                {geometryTypesLoading ? (
                                    <MenuItem value="">
                                        <CircularProgress size={20} sx={{ mr: 1 }} />
                                        加载中...
                                    </MenuItem>
                                ) : (
                                    effectiveGeometryTypes.map((type) => (
                                        <MenuItem key={type.type} value={type.type}>
                                            {type.displayName}
                                        </MenuItem>
                                    ))
                                )}
                            </Select>
                            {validationErrors.geometryType && (
                                <Typography color="error" variant="caption">
                                    {validationErrors.geometryType}
                                </Typography>
                            )}
                        </FormControl>
                    </Grid>

                    <Grid item xs={12} sm={6}>
                        <Box>
                            <Typography variant="subtitle2" gutterBottom>
                                颜色
                            </Typography>
                            <Box
                                sx={{
                                    display: 'flex',
                                    alignItems: 'center'
                                }}
                            >
                                <Box
                                    sx={{
                                        width: 40,
                                        height: 40,
                                        borderRadius: 1,
                                        border: '1px solid #ddd',
                                        backgroundColor: color,
                                        cursor: 'pointer',
                                        mr: 2
                                    }}
                                    onClick={() => setShowColorPicker(!showColorPicker)}
                                />
                                <Typography>
                                    {color}
                                </Typography>
                            </Box>
                            {showColorPicker && (
                                <Box sx={{ mt: 2, position: 'relative', zIndex: 2 }}>
                                    <Box
                                        sx={{
                                            position: 'fixed',
                                            top: 0,
                                            right: 0,
                                            bottom: 0,
                                            left: 0
                                        }}
                                        onClick={() => setShowColorPicker(false)}
                                    />
                                    <ChromePicker
                                        color={color}
                                        onChange={(colorResult) => setColor(colorResult.hex)}
                                    />
                                </Box>
                            )}
                        </Box>
                    </Grid>
                </Grid>

                <Box sx={{ mt: 3 }}>
                    {geometryType && renderGeometryAttributes()}
                </Box>
            </Paper>

            <Paper sx={{ p: 3, mb: 3 }}>
                <Typography variant="h6" gutterBottom>
                    位置与旋转
                </Typography>

                <Typography variant="subtitle2" gutterBottom>
                    位置
                </Typography>
                <Grid container spacing={2} sx={{ mb: 3 }}>
                    <Grid item xs={12} sm={4}>
                        <TextField
                            label="X 坐标"
                            fullWidth
                            type="number"
                            value={positionX}
                            onChange={(e) => setPositionX(e.target.value)}
                            inputProps={{ step: 0.1 }}
                        />
                    </Grid>
                    <Grid item xs={12} sm={4}>
                        <TextField
                            label="Y 坐标"
                            fullWidth
                            type="number"
                            value={positionY}
                            onChange={(e) => setPositionY(e.target.value)}
                            inputProps={{ step: 0.1 }}
                        />
                    </Grid>
                    <Grid item xs={12} sm={4}>
                        <TextField
                            label="Z 坐标"
                            fullWidth
                            type="number"
                            value={positionZ}
                            onChange={(e) => setPositionZ(e.target.value)}
                            inputProps={{ step: 0.1 }}
                        />
                    </Grid>
                </Grid>

                <Typography variant="subtitle2" gutterBottom>
                    旋转（度）
                </Typography>
                <Grid container spacing={2}>
                    <Grid item xs={12} sm={4}>
                        <TextField
                            label="X 轴旋转"
                            fullWidth
                            type="number"
                            value={rotationX}
                            onChange={(e) => setRotationX(e.target.value)}
                            inputProps={{ step: 5, min: 0, max: 360 }}
                        />
                    </Grid>
                    <Grid item xs={12} sm={4}>
                        <TextField
                            label="Y 轴旋转"
                            fullWidth
                            type="number"
                            value={rotationY}
                            onChange={(e) => setRotationY(e.target.value)}
                            inputProps={{ step: 5, min: 0, max: 360 }}
                        />
                    </Grid>
                    <Grid item xs={12} sm={4}>
                        <TextField
                            label="Z 轴旋转"
                            fullWidth
                            type="number"
                            value={rotationZ}
                            onChange={(e) => setRotationZ(e.target.value)}
                            inputProps={{ step: 5, min: 0, max: 360 }}
                        />
                    </Grid>
                </Grid>
            </Paper>

            <AnimatePresence>
                {error && (
                    <motion.div
                        initial={{ opacity: 0, y: -10 }}
                        animate={{ opacity: 1, y: 0 }}
                        exit={{ opacity: 0 }}
                    >
                        <Alert severity="error" sx={{ mb: 3 }}>
                            {error}
                        </Alert>
                    </motion.div>
                )}
            </AnimatePresence>

            <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
                {onCancel && (
                    <Button
                        variant="outlined"
                        onClick={onCancel}
                        disabled={loading}
                    >
                        取消
                    </Button>
                )}
                <Button
                    type="submit"
                    variant="contained"
                    disabled={loading}
                    sx={{ minWidth: 120 }}
                >
                    {loading ? <CircularProgress size={24} /> : isEdit ? '更新' : '创建'}
                </Button>
            </Box>
        </Box>
    );
};

export default GeometryModelForm; 